package org.fxd.zweixin.util;

import java.net.NetworkInterface;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.tmsps.ne4spring.utils.WebUtil;


public class IPTools {

	public static String getIP() {
		HttpServletRequest req = WebUtil.getRequest();
		String ip = req.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getRemoteAddr();
		}

		return ip;
	}

	public static String getMac() {
		String mac = "";
		try {
			Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
			while (enumeration.hasMoreElements()) {
				StringBuffer stringBuffer = new StringBuffer();
				NetworkInterface networkInterface = enumeration.nextElement();
				if (networkInterface != null) {
					byte[] bytes = networkInterface.getHardwareAddress();
					if (bytes != null) {
						for (int i = 0; i < bytes.length; i++) {
							if (i != 0) {
								stringBuffer.append("-");
							}
							int tmp = bytes[i] & 0xff; // 字节转换为整数
							String str = Integer.toHexString(tmp);
							if (str.length() == 1) {
								stringBuffer.append("0" + str);
							} else {
								stringBuffer.append(str);
							}
						}
						mac = stringBuffer.toString().toUpperCase();
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mac;
	}
}
